<?php
namespace Agent\Controller;
use Think\Controller;
class BookController extends BaseController {
    public function _initialize()
    {
        parent::_initialize();
        $g=session('agent');
        $db_name=$g['db'];
		C('erp_dbname',$g['db']);
        $this->product = M('book',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $db_name);
		//数据库连接基础配置-begin
		C('db_config.DB_TYPE',C('DB_TYPE'));
		C('db_config.DB_HOST',C('DB_HOST'));
		C('db_config.DB_USER',C('DB_USER'));
		C('db_config.DB_PWD',C('DB_PWD'));
		C('db_config.DB_PORT',C('DB_PORT'));
		C('db_config.DB_CHARSET',C('DB_CHARSET'));
		//数据库连接基础配置-end
    }
	//账册同步(默认以仓库为准来对应账册,仓库中对应货主的账册一定是唯一)--按erp对应关系（主erp-货主）来同步
	public function syn_book(){
		//数据库连接基础配置-begin
		C('db_config1.DB_TYPE',C('DB_TYPE'));
		C('db_config1.DB_HOST',C('DB_HOST'));
		C('db_config1.DB_USER',C('DB_USER'));
		C('db_config1.DB_PWD',C('DB_PWD'));
		C('db_config1.DB_PORT',C('DB_PORT'));
		C('db_config1.DB_CHARSET',C('DB_CHARSET'));
		C('db_config1.DB_NAME',C('erp_dbname'));
		//数据库连接基础配置-end
		//商家编码
		$g=session('agent');
        $db_name=$g['db'];
		$m=M('user');
		$w=M('Warehouse');
		$uw=M('UserWarehouse');
		$user_id=session('agent.id');
		$merchant_code=C('base_config.merchant_code');
		$bb=M('Book',C('DB_PREFIX_T'), C('db_config1'));//账册名称
		$pp=M('Product',C('DB_PREFIX_T'), C('db_config1'));//账册详情
		//货主判断
		$owner_status=session('agent.owner_status');//货主属性0:否1是
		$this->assign('owner_status',$owner_status);
		if($owner_status){//是货主（允许同步账册）
			$info=$m->where(array('id'=>$user_id))->find();
			$m_list=explode(',',$info['erp_code']);
			// dump($m_list);
			// die;
			if(!empty($m_list)){
				foreach($m_list as $k=>$v){
					$m_info=$m->where(array('id'=>$v))->find();
					$username=$m_info['username'];
					$erp_dbname=C('DB_PREFIX_T').$username;//erp对应数据库名称
					C('db_config.DB_NAME',$erp_dbname);
					$b=M('Book',C('DB_PREFIX_T'), C('db_config'));//账册名称
					$p=M('Product',C('DB_PREFIX_T'), C('db_config'));//账册详情
					$b_info=$b->where(array('merchant_code'=>$merchant_code))->find();//获得对应erp的账册信息
					if(empty($b_info)){
						alert_json(0,'没有找到账册信息，请通知服务商添加后再同步');
					}
					$p_list=$p->where(array('zccode'=>$b_info['book_no']))->select();
					foreach($p_list as $ks=>$vs){
						unset($p_list[$ks]['id']);
					}
					unset($b_info['id']);
					if(!$k){
						$d_bb=$bb->where(array('book_no'=>$b_info['book_no']))->delete();//清空账册对应原先信息
						if($d_bb===false){
							alert_json(0,'清空账册信息失败');
						}
						$d_pp=$pp->where(array('zccode'=>$b_info['book_no']))->delete();//清空账册详情对应原先信息
						if($d_pp===false){
							alert_json(0,'清空账册详情信息失败');
						}
					}
					$res_bb=$bb->add($b_info);//插入账册
					if(!$res_bb){
						alert_json(0,'插入账册信息失败');
					}
					$res_pp=$pp->addAll($p_list);//插入账册详情
					if(!$res_pp){
						alert_json(0,'插入账册详情信息失败');
					}
				}
				alert_json(1,'同步成功');
			}else{
				alert_json(0,'未绑定主erp');
			}
		}else{
			alert_json(0,'不是货主，不能同步！');
		}
	}
	//账册同步(默认以仓库为准来对应账册,仓库中对应货主的账册一定是唯一)
	public function syn_book_old(){
		//商家编码
		$g=session('agent');
        $db_name=$g['db'];
		$m=M('user');
		$w=M('Warehouse');
		$uw=M('UserWarehouse');
		$user_id=session('agent.id');
		$merchant_code=C('base_config.merchant_code');
		$bb=M('Book',C('DB_PREFIX_T'), C('db_config'));//账册名称
		$pp=M('Product',C('DB_PREFIX_T'), C('db_config'));//账册详情
		
		$uw_info=$uw->where(array('user_id'=>$user_id))->find();
		$warehouse_idlist=array_unique(explode(',',$uw_info['warehouse_group_id']));
		$warehouse_list=$w->where(array('id'=>array('in',$warehouse_idlist)))->select();
		foreach($warehouse_list as $k=>$v){
			$wms_dbname=$v['db_name'];//仓库对应数据库名称
			C('db_config.DB_NAME',$wms_dbname);
			$bc=M('books_cate',C('DB_PREFIX_TT'), C('db_config'));
			$bc_info=$bc->field('erp_code,code')->where(array('merchant_code'=>$merchant_code))->find();//货主信息对应erp_code,账册编码（仓库对应货主账册一定是唯一）
			// echo $bc->getlastsql();
			// dump($bc_info);
			// die;
			if($k>0){
				if($bc_info['code']==$old_book_no){
					continue;
				}
			}
			$username=$m->where(array('id'=>$bc_info['erp_code']))->getField('username');
			$erp_dbname=C('DB_PREFIX_T').$username;//erp对应数据库名称
			$b=M('Book',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $erp_dbname);//账册名称
			$p=M('Product',C('DB_PREFIX_T'), C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $erp_dbname);//账册详情
			$b_info=$b->where(array('merchant_code'=>$merchant_code,'book_no'=>$bc_info['code']))->find();//获得对应erp的账册信息
			if(empty($b_info)){
				alert_json(0,'没有找到账册信息，请通知服务商添加后再同步');
			}
			$old_book_no=$bc_info['code'];
			$p_list=$p->where(array('zccode'=>$b_info['book_no']))->select();
			foreach($p_list as $ks=>$vs){
				unset($p_list[$ks]['id']);
			}
			unset($b_info['id']);
			$d_bb=$bb->where(array('book_no'=>$b_info['book_no']))->delete();//清空账册对应原先信息
			if($d_bb===false){
				alert_json(0,'清空账册信息失败');
			}
			$d_pp=$pp->where(array('zccode'=>$b_info['book_no']))->delete();//清空账册详情对应原先信息
			if($d_pp===false){
				alert_json(0,'清空账册详情信息失败');
			}
			$res_bb=$bb->add($b_info);//插入账册
			if(!$res_bb){
				alert_json(0,'插入账册信息失败');
			}
			$res_pp=$pp->addAll($p_list);//插入账册详情
			if(!$res_pp){
				alert_json(0,'插入账册详情信息失败');
			}
		}
		alert_json(1,'同步成功');
	}
	
    public function index(){
        if(!isset($_GET['p']) || $_GET['p']==''){
            $p=1;
        }else{
            $p=intval($_GET['p']);
        }
        if(I("get.start_time")!='') {
            $where['created_at']= array('gt',I("get.start_time"));
        }
        if(I("get.end_time")!=''){
            $where['created_at'] = array('lt',I("get.end_time"));
        }
        if(I("get.start_time")!='' && I("get.end_time")!=''){
            $where['created_at']= array(array('gt',I("get.start_time")),array('lt',I("get.end_time")));
        }
        if(I("get.name")!=''){
            $where['name']=array('like',"%".I("get.name")."%");
        }
        if(I("get.page_count")=='' || I("get.page_count")<=0){
            $page_count=15;
        }else{
            $page_count=intval(I("get.page_count"));
        }
        if(I("get.sort")!=''){
            $order=I("get.sort")." ".I("get.dec");
        }else{
            $order='id desc';
        }
        if(!isset($where)){
            $where="1=1";
        }
        $list = $this->product->where($where)->order($order)->page($p.','.$page_count)->select();
        $this->assign('list',$list);
        $count      = $this->product->where($where)->count();
        $this->assign('count',$count);
        $Page       = new \Think\Page($count,$page_count);
        $show       = $Page->show();
        $this->assign('page',$show);
        $this->display();
    }
    public function add(){
        $this->display();
    }
    public function addD($name,$book_no,$type,$merchant_code){
        if($name==''){
            alert(0,'账册名称不能为空');
        }
        if($book_no==''){
            alert(0,'账册编号不能为空');
        }
		if($merchant_code==''){
            alert(0,'商家编号不能为空');
        }
        if($type!=1 && $type!=2){
            alert(0,'请选择账册类型');
        }
        $data['name']=$name;
        $data['book_no']=$book_no;
		$data['merchant_code']=$merchant_code;
        $data['type']=$type;
        $massage=session('agent');
        $data['operator']=$massage['username'];
        if($this->product->where(array('name'=>$name))->count()>0){
            alert(0,'账册名称不能重复');
        }
        if($this->product->where(array('book_no'=>$book_no))->count()>0){
            alert(0,'账册编号不能重复');
        }
        $result=$this->product->add($data);
        if($result){
            alert(1,'添加成功');
        }else{
            alert(0,'添加失败');
        }
    }
    public function getWarehouse(){
        $g=session('agent');
        $user_id=$g['company_id'];
        $group_id=M("user_warehouse")->where(array('user_id'=>$user_id))->getField('warehouse_group_id');
        $group_id=explode(',',$group_id);
        $where['id']=array('in',$group_id);
        $result=M("warehouse")->where($where)->getField('id,name',true);
        if($result){
            alert(1,$result);
        }else{
            alert(0,'暂无仓库信息');
        }
    }
    public function push($id,$warehouse_id){
        $g=session('agent');
        $db_name=$g['db'];
        $user_id=$g['company_id'];
        $f=C('DB_PREFIX_T');
        $this->p = M('book',$f, C('DB_TYPE') . '://' . C('DB_USER') . ':' . C('DB_PWD') . '@' . C('DB_HOST') . ':' . C('DB_PORT') . '/' . $db_name);
        $list=$this->p->where("id='".$id."'")->find();
        $list['erp_code']=$g['company_id'];
        //////如果已经推送则不能再次推送
        if($list['examined']>0){
           // alert(0,'请不要重复推送');
        }
        unset($list['examined']);
        $g_id=M("user_warehouse")->where(array('user_id'=>$user_id))->getField('warehouse_group_id');
        $group_id=explode(',',$g_id);
        if(!in_array($warehouse_id,$group_id)){
            alert(0,'操作有误');
        }
        $d=M("warehouse")->join("__INTERFACES__ on __INTERFACES__.warehouse_id=__WAREHOUSE__.id")->where(C('DB_PREFIX')."warehouse.id='".$warehouse_id."'")->getField('vars,url,warehouse_code');
        $url=$d['var_5']['url'];
        $data=array(
            'erp_code'=>$g['company_id'],
            'warehouse_code'=>$d['var_5']['warehouse_code'],
            'list'=>$list,
        );
        $true=push($url,$data);//推送过去
		$true=json_decode(trim($true,'﻿'),true);//替换掉utf8 BOM格式编码字符
        if($true['status']==1){
            if($this->product->where("id='".$id."'")->setField('examined',1)){
                alert(1,$true['info']);
            }else{
                alert(0,'推送成功，状态更新失败');
            }
        }else{
            alert(0,$true['info']);
        }
    }
    public function edit($id){
        if($id==''){
            echo "错误";
        }
        $this->result=$this->product->find($id);
        $this->display();
    }
    public function editD($id,$name,$book_no,$type,$merchant_code){
        if($name==''){
            alert(0,'账册名称不能为空');
        }
        if($book_no==''){
            alert(0,'账册编号不能为空');
        }
		if($merchant_code==''){
            alert(0,'商家编号不能为空');
        }
        if($type!=1 && $type!=2){
            alert(0,'请选择账册类型');
        }
        $data['name']=$name;
        $data['book_no']=$book_no;
		$data['merchant_code']=$merchant_code;
        $data['type']=$type;
        $where['name']=$name;
        $where['id']=array('neq',$id);
        if($this->product->where($where)->count()>0){
            alert(0,'账册名称不能重复');
        }
        $wheres['book_no']=$book_no;
        $wheres['id']=array('neq',$id);
        if($this->product->where($wheres)->count()>0){
            alert(0,'账册编号不能重复');
        }
        $massage=session('agent');
        $data['operator']=$massage['username'];
		$data['examined']=0;
		
        $result=$this->product->where("id='".$id."'")->save($data);
        if($result){
            alert(1,'修改成功');
        }else{
            alert(0,'修改失败');
        }
    }
    public function del($id){
        ///////$id=1@2@3
        $group_id=explode('@',$id);
        $id=implode(',',$group_id);
        $result=$this->product->delete($id);
        if($result){
            alert(1,'成功删除了'.$result.'条数据，共'.count($group_id).'条');
        }else{
            alert(0,'删除失败');
        }
    }
}